<template>
  <ElSelect
      v-model="selectedValue"
      filterable
      clearable
      :="$attrs"
      placeholder=""
  >
    <ElOption v-for="item in options" :key="item.name" :label="item.val" :value="item.name"/>
  </ElSelect>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { ElSelect, ElOption } from 'element-plus'
import { getdictIdList } from '../api'

interface Props {
  modelValue: string | null // 接收 v-model 的值
  data: any
}

const props = defineProps<Props>()
const emit = defineEmits<{
  (e: 'update:modelValue', value: string | null): void
}>()

const selectedValue = ref(props.modelValue)
const options = ref<Array<{ val: string, name: string }>>([])

// 监听外部传入的 modelValue 变化
watch(() => props.modelValue, (newVal) => {
  selectedValue.value = newVal
})

// 监听 selectedValue 内部变化并同步到父组件
watch(selectedValue, (newVal) => {
  emit('update:modelValue', newVal)
})

const getOptions = () => {
  if (props.data.tsjgpdVal === '有效') {
    getdictIdList({ parentId: 1031 }).then(res => {
      options.value = res
    })
  } else if (props.data.tsjgpdVal === '无效') {
    options.value = [{ val: '无', name: '无' }]
  } else {
    options.value = []
  }
}

// 监听 tsjgpdVal变化 清空当前选择
watch(() => props.data.tsjgpdVal, () => {
  selectedValue.value = null
  emit('update:modelValue', null)
  getOptions()
},{ deep: true })

getOptions()
</script>